package com.example.springbootrabbitmq.producer;

import com.example.springbootrabbitmq.constant.Constant;
import com.example.springbootrabbitmq.entity.MessageLog;
import com.example.springbootrabbitmq.entity.TOrder;
import com.example.springbootrabbitmq.mapper.MessageLogMapper;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * @author hl
 */
@Component
public class OrderSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MessageLogMapper messageLogMapper;

    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            String messageId = correlationData.getId();
            if(ack){
                /**
                 * confirm返回成功
                 * 更新消息
                 */
                MessageLog messageLog = new MessageLog();
                messageLog.setId(messageId);
                messageLog.setStatus(Constant.ORDER_SUCCESS);
                messageLog.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                messageLogMapper.updateById(messageLog);
            } else {
                /**
                 * confirm返回失败
                 * 进行补偿操作
                 */
            }
        }
    };

    public void sendOrder(TOrder tOrder) throws Exception {
        /**
         * 设置回调函数
         */
        rabbitTemplate.setConfirmCallback(confirmCallback);

        /**
         *发送消息
         */
        CorrelationData correlationData = new CorrelationData(tOrder.getMessageId());
        rabbitTemplate.convertAndSend(
                // 指定交换机
                "order-exchange11111",
                // 指定路由规则
                "order.queue",
                // 消息体内容
                tOrder,
                // 消息ID
                correlationData
        );
    }
}
